import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.util.Map;

/**
 * @author huangguo
 * @time 19-7-27 下午12:48
 */
public class EsInsert {
    public static void main(String[] args) {
        try {

            //设置集群名称

            Settings settings = Settings.builder().put("cluster.name", "mojito").build();
            //创建client
            @SuppressWarnings("resource")
            TransportClient client = new PreBuiltTransportClient(settings)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
            //写入数据
            System.out.println("123");
            // createDate(client);
            //搜索数据
            GetResponse response = client.prepareGet("gtbdc", "ql_xz", "SCH30761").execute().actionGet();
            //输出结果
            System.out.println(response.getSource());
            long startTimeall = System.currentTimeMillis();
            for (int i = 100; i < 200; i++) {
                long startTime = System.currentTimeMillis();
                createManyDates(client, response.getSource(), i);
                long endTime = System.currentTimeMillis(); // 获取结束时间
                System.out.println("十万条插入时间： " + (endTime - startTime) + "ms");
            }
            long endTimeall = System.currentTimeMillis(); // 获取结束时间
            System.out.println("所有运行时间： " + (endTimeall - startTimeall) + "ms");

            //关闭client
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void createManyDates(TransportClient client, Map<String, Object> map, Integer j){
        int count = (j*100000+1);
        int k = j*100000;
        String index = "gtbdc";
        String type = "others";
        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
        for(int i = (j-1)*100000+1;i <count;i++){
            map.put("bdcqzh", i);
            //Map<String, Object> map = new HashMap<String, Object>();
            bulkRequestBuilder.add(client.prepareIndex(index, type, i+"").setSource(map));
            if(i%k ==0){
                bulkRequestBuilder.execute().actionGet();
            }
        }

    }
}
